#!/usr/bin/env bash

set -eu

mkdir -p $HOME/rpmbuild/SOURCES

if [ -e "/src/rpm/SOURCES/darling.tar.gz" ]; then
  ln -sf /src/rpm/SOURCES/darling.tar.gz $HOME/rpmbuild/SOURCES/
else
  # Preparing tarball
  tar --transform "s|^\./|./darling/|" -cf $HOME/rpmbuild/SOURCES/darling.tar.gz -C /src --exclude=.git --exclude SOURCES --exclude SRPMS --exclude RPMS --exclude BUILD .
fi

if [ -e "/src/rpm/SOURCES/darling-macho-deps.tar.gz" ]; then
  ln -sf /src/rpm/SOURCES/darling-macho-deps.tar.gz $HOME/rpmbuild/SOURCES/
else
  tar --transform "s|^\./|darling-macho-deps/|" -cf $HOME/rpmbuild/SOURCES/darling-macho-deps.tar.gz -C /src/tools/rpm .
fi

if (cd /src && git describe --tags HEAD); then
  DARLING_COMMIT_DATE="$(cd /src; git describe --tags HEAD)"
  export DARLING_COMMIT_DATE="${DARLING_COMMIT_DATE//-/}"
else
  # default to the current date
  export DARLING_COMMIT_DATE="$(printf '%(%Y%m%d)T\n' -1)"
fi

rpmbuild -bb /src/rpm/SPECS/darling-macho-deps.spec
sudo rpm -U --force $HOME/rpmbuild/RPMS/x86_64/darling-macho-deps*.rpm

#spectool -g -R /src/rpm/SPECS/darling.spec
rpmbuild -bb /src/rpm/SPECS/darling.spec
rpmbuild -bb /src/rpm/SPECS/darling-cli-devenv.spec
